﻿using DNFImagePacks2Manager.Helpers;
using DNFImagePacks2Manager.Pages;
using DNFImagePacks2Manager.QuickTool.Models;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Animation;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Storage;
using WinUIEx;

namespace DNFImagePacks2Manager
{
    // 主窗口
    public sealed partial class MainWindow : Window
    {
        // 置顶定时器
        private readonly DispatcherTimer _topmostTimer;

        // 默认页面切换动画
        private readonly NavigationTransitionInfo DeafultNavigationTransitionInfo = new DrillInNavigationTransitionInfo();

        public Page? CurrentPage => rootFrame.Content as Page;

        // 页面字典
        private readonly Dictionary<string, Type> chindPages = new()
        {
            // 主页
            {"Home", typeof(HomePage)},
            // 内置浏览器
            {"WebViewColg", typeof(WebViewPage)},
            // 文件导入页面
            {"FileLoad", typeof(FileLoadPage)},
            // NPK列表页面
            {"ListNPK", typeof(ListNPKPage)},
            // NPK清空页面
            {"ClearNPK", typeof(NPKClearPage)},
            // BK列表页面
            {"ListBK", typeof(ListBKPage)},
            // 官方NPK页面
            {"OfficialNPK", typeof(OfficialNPKPage)},
            // 官方BK页面
            {"OfficialBK", typeof(OfficialBKPage)},
            // 个性化配置列表页面
            {"ListCustom", typeof(ListCustomPage)},
            // 小工具列表
            {"ListTool", typeof(ListQuickToolPage)},
            // 设置页面
            {"Settings", typeof(SettingsPage)},
            // 文件导入进度页面
            {"ProcessLoad", typeof(ProcessLoadPage)},
            // 文件导出进度页面
            {"ProcessExport", typeof(ProcessExportPage)},
            // 保存BK套装进度页面
            {"ProcessSaveBK", typeof(ProcessSaveBKPage)},
            // NPK生成小工具页面
            {"ImgReplace", typeof(QuickToolImgReplacePage)},
            // NPK合并小工具页面
            {"ImgMerge", typeof(QuickToolImgMergePage)},
            // NPK拆分小工具页面
            {"ImgSplit", typeof(QuickToolImgSplitPage)}
        };

        // 主窗口构造方法
        public MainWindow()
        {
            this.InitializeComponent();
            // 监听窗口关闭事件
            this.Closed += MainWindow_Closed;
            // 初始化界面
            LoadAllSettings();
            // 初始化置顶定时器
            _topmostTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(2)
            };
            _topmostTimer.Tick += (s, e) =>
            {
                this.SetIsAlwaysOnTop(false);
                _topmostTimer.Stop();
            };
        }

        private void LoadAllSettings()
        {
            // 设置标题栏
            this.ExtendsContentIntoTitleBar = true;
            this.SetTitleBar(titleBar);
            this.AppWindow.SetIcon("Assets/app.ico");
            this.AppWindow.TitleBar.PreferredHeightOption = TitleBarHeightOption.Tall;
            // 设置应用主题
            ThemeTool.InitAppTheme(this);
            // 初始化窗口大小
            this.InitWindowSize();
            // 窗口居中
            this.CenterOnScreen();
        }

        // 窗口关闭事件
        private void MainWindow_Closed(object sender, WindowEventArgs args)
        {
            try
            {
                // 记忆窗口尺寸
                WindowManager windowManager = WindowManager.Get(this);
                if (windowManager.WindowState == WindowState.Normal)
                {
                    var size = windowManager.AppWindow.Size;
                    LocalStorageHelper.SetWindowSize(size.Width, size.Height);
                }
            }
            catch{}
        }

        // 激活窗口并置顶
        public void ActivateAndFront()
        {
            this.Activate();

            WindowManager windowManager = WindowManager.Get(this);
            if (windowManager.WindowState == WindowState.Minimized)
            {
                windowManager.WindowState = WindowState.Normal;
            }

            this.SetIsAlwaysOnTop(true);

            if (_topmostTimer.IsEnabled)
            {
                _topmostTimer.Stop();
            }
            _topmostTimer.Start();
        }

        // 初始化窗口大小
        private void InitWindowSize()
        {
            bool isValid = LocalStorageHelper.GetWindowSize(out int width, out int height);
            if (isValid) {
                WindowManager windowManager = WindowManager.Get(this);
                if (windowManager.WindowState == WindowState.Normal)
                {
                    windowManager.AppWindow.Resize(new() {
                        Width = width,
                        Height = height
                    });
                }
            }
        }

        // 修改设置文字
        private void OnNavigationViewControlLoaded(object sender, RoutedEventArgs e)
        {
            if (NavigationViewControl.SettingsItem is NavigationViewItem settingsItem)
            {
                settingsItem.Content = "设置";
            }
        }

        // 列表点击事件
        private void OnNavigationViewItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
        {
            if (args.IsSettingsInvoked)
            {
                ChangePage("Settings");
            }
            else
            {
                var invokedItem = args.InvokedItemContainer as NavigationViewItem;
                if (invokedItem != null)
                {
                    string pageName = invokedItem.Name;
                    if (chindPages.ContainsKey(pageName))
                    {
                        ChangePage(pageName);
                    }
                }
            }
        }

        // 切换页面
        public void ChangePage(string pageName, object? targetPageArguments = null, NavigationTransitionInfo? navigationTransitionInfo = null)
        {
            var pageType = chindPages[pageName];
            if (rootFrame.Content?.GetType() == pageType)
            {
                // 如果页面相同，可重载页面触发重载方法
                if (rootFrame.Content is IReloadablePage reloadablePage)
                {
                    reloadablePage.ReloadPage();
                }
            }
            else
            {
                // 如果页面不同，切换页面
                if (navigationTransitionInfo == null)
                {
                    navigationTransitionInfo = DeafultNavigationTransitionInfo;
                }
                rootFrame.Navigate(pageType, targetPageArguments, navigationTransitionInfo);
            }
        }

        // 切换到文件导入进度页面
        public void ChangeProcessLoadPage(List<StorageFile> files)
        {
            ChangePage("ProcessLoad");

            if (rootFrame.Content is ProcessLoadPage addPage)
            {
                _ = Task.Run(() => addPage.StartImportTask(files));
            }
        }

        // 切换到文件导出进度页面
        public void ChangeProcessExportPage(Dictionary<string, string> compressFiles, string exportFile)
        {
            ChangePage("ProcessExport");

            if (rootFrame.Content is ProcessExportPage exportPage)
            {
                _ = Task.Run(() => exportPage.StartExportTask(compressFiles, exportFile));
            }
        }

        // 切换到BK套装保存进度页面
        public void ChangeProcessSaveBKPage(string saveName, bool addWhole, bool isCustom)
        {
            ChangePage("ProcessSaveBK");

            if (rootFrame.Content is ProcessSaveBKPage savePage)
            {
                _ = Task.Run(() => savePage.StartExportTask(saveName, addWhole, isCustom));
            }
        }

        public void ChangeAndInitializePage(string pageName, object item)
        {
            ChangePage(pageName);

            if (rootFrame.Content is IInitializable page)
            {
                page.InitializePage(item);
            }
        }
    }
}
